﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MSH.Common.Helpers;
using System.Timers;
using NHibernate;
using NHibernate.Linq;
using MSH.Common.Business;
using Facebook;
using System.Threading.Tasks;

namespace MSH.TaskServer.Tasks
{
    /// <summary>
    /// Taak die ervoor zorgt dat het huidige profiel aangevuld word met facebook data en de facebook vrienden in de database opgeslagen worden.
    /// </summary>
    public class FacebookTask
    {
        private System.Timers.Timer timer;

        public FacebookTask()
        {
            timer = new System.Timers.Timer(int.Parse(System.Configuration.ConfigurationManager.AppSettings["facebookTaskInterval"].ToString()));
            timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            timer.Enabled = true;
  
            LogHelper.LogMessage(String.Format("FacebookTask(): task scheduled (interval = {0} minutes)", timer.Interval / 1000 / 60));

            OnTimedEvent(null, null);
        }

        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            LogHelper.LogMessage("FacebookTask.OnTimedEvent()");
            timer.Enabled = false;
            try
            {
                using (ISession session = NHibernateHelper.GetSessionFactory().OpenSession())
                {
                    IQuery q = session.CreateSQLQuery("SELECT US.USERNAME FROM \"USER\" US INNER JOIN USERSOCIALNETWORKACCOUNT UNA ON UNA.ACCOUNTTYPE = 'Facebook' AND UNA.PARENTUSER = US.ID");

                    IList<String> facebookUsers = q.List<String>();

                    Parallel.ForEach<String>(facebookUsers, (username) => FacebookHelper.UpdateFacebookData(username));

                    Parallel.ForEach<String>(facebookUsers, (username) => FacebookHelper.GetFacebookFriends(username));
                }
            }
            finally
            {
                LogHelper.LogMessage("FacebookTask.OnTimedEvent(): Done");
                timer.Enabled = true;
            }
        }

     
    }
}
